﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using hedefgrup.reports.renault.definitions;
using hedefgrup.reports.renault;
using hedefgrup.reports.renault.calculators;
using hedefgrup.reports.renault.implementation;
using hedefgrup.reports.renault.date;
using System.Collections.Generic;
using System.Globalization;

public partial class forms_rankingResults_rankingResults : reportPage
{
    private const string SUMMARY_TABLE_HEADER_CELL_TEMPLATE = "<td width='30%' height=18px align=center class=t_head >{0}</td>";
    private const string SUMMARY_TABLE_VALUE_CELL_TEMPLATE = "<td width='70%' height=18px align='left' class=vktxt8 >{0}</td>";
    private const string REPORT_TABLE_HEADER_CELL_TEMPLATE = "<td width={0}px height=38px align=center class=t_head valign=center>{1}</td>";
    private const string REPORT_CELL_TEMPLATE = "<td style='text-align:right;' class=vktxt8 >{0}</td>";
    private const string REPORT_TEXT_CELL_TEMPLATE = "<td style='text-align:left;' class=vktxt8 >{0}</td>";

    private static CultureInfo english = CultureInfo.GetCultureInfo("en-US");

    protected override string getReportFileName()
    {
        return "BAYII SIRALAMA - " + base.getReportFileName();
    }

    private static string generateReportTableHeaderCell(string text, int width)
    {
        return string.Format(REPORT_TABLE_HEADER_CELL_TEMPLATE, width, text);
    }

    private static string generateReportTableHeaderCell(questionDefinition questionToReport, int width)
    {
        return generateReportTableHeaderCell(questionToReport.getCode() + " - " + questionToReport.getName(), width);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        base.initialize();
        base.ensureUserIsLoggedIn();

        excelReportName.Text = base.getReportFileName();

        questionDefinition rankingQuestion = base.getDataCache().questionDefinitions[Request.Form["rankingCriteria"].Split(':')[0]];
        if (excelExportDiv.Visible) excelExportDiv.Visible = !IsExcelDownloadRequest;

        StringBuilder htmlBuilder = new StringBuilder();

        htmlBuilder = new StringBuilder();

        htmlBuilder.Append(generateReportTableHeaderCell("Sıra", 40));
        htmlBuilder.Append(generateReportTableHeaderCell("Bayii", 260));

        htmlBuilder.Append(generateReportTableHeaderCell(rankingQuestion, 120));

        reportTableHeaderHtml.Text = htmlBuilder.ToString();

        reportDealerInfo[] dealersInfos = base.getCalculator().generateReportDataForMultipleDealers
        (
            base.getCalculatorType(),
            base.selectedMonth - (base.cumulativeMonths - 1),
            base.selectedMonth
        );

        reportRowDefinition rankingReportRow = null;
        reportDefinition report = base.getDataCache().reportDefinitions["dealerTargets"];
        foreach (reportRowDefinition rowDefinition in report.rowDefinitions)
        {
            if
            (
                rowDefinition.getQuestionToReport() == rankingQuestion.getCode()
                &&
                rowDefinition.getAttributeByName("o") == Request.Form["rankingCriteria"].Split(':')[1]
            )
            {
                rankingReportRow = rowDefinition;
                break;
            }
        }

        bool monitoredDealersOnly = Request.Form["dealerListType"] == "monitoredOnly";

        List<RankingInfo> rankingInfos = new List<RankingInfo>();

        htmlBuilder.Length = 0;

        foreach (reportDealerInfo dlr in dealersInfos)
        {
            if
            (
                dlr.dealer.getTypeCode() != "dealer"
                &&
                dlr.dealer.getTypeCode() != "branch"
                &&
                dlr.dealer.getTypeCode() != "satellite"
                &&
                dlr.dealer.getTypeCode() != "connected_point"
                &&
                dlr.dealer.getTypeCode() != "network1"
                &&
                dlr.dealer.getTypeCode() != "network2"
            ) continue;

            if (dlr.data.baseCount == 0) continue;

            if (monitoredDealersOnly && dlr.dealer.getAttributeByName("monitor") != "true") continue;

            List<string> userDealerCodes = new List<string>(base.getUserDealerCodes());
            if (userDealerCodes.Count == 0 || userDealerCodes.Contains(dlr.dealer.getCode()))
            {
                question questionToReport = dlr.data.questions[rankingQuestion.getCode()];
                double dealerRankValue = 0;
                switch (rankingReportRow.getRowType())
                {
                    case "percentage_of_option":
                        dealerRankValue = questionToReport.calculateOptionPercentage(Convert.ToInt32(rankingReportRow.getAttributeByName("o")));
                        break;
                    case "formula_1":
                        dealerRankValue = questionToReport.calculateFormula1();
                        break;
                    case "percentage_over_total_base":
                        string[] optionsToReport = rankingReportRow.getAttributeByName("o").Split(',');
                        foreach (string optionToReportString in optionsToReport)
                        {
                            int optionToReport = Convert.ToInt32(optionToReportString);
                            dealerRankValue += questionToReport.getOptionCount(optionToReport);
                        }
                        dealerRankValue = dealerRankValue / (double)dlr.data.baseCount;
                        break;
                }
                rankingInfos.Add(new RankingInfo(dlr.dealer, dealerRankValue));
            }
        }

        rankingInfos.Sort();

        if (rankingReportRow.getAttributeByName("op") == "<")
        {
            rankingInfos.Reverse();
        }

        int rankOfDealer = 1;
        foreach (RankingInfo rankingInfo in rankingInfos)
        {
            htmlBuilder.Append("<tr>");
            htmlBuilder.AppendFormat(REPORT_CELL_TEMPLATE, rankOfDealer++);
            htmlBuilder.AppendFormat(REPORT_TEXT_CELL_TEMPLATE, rankingInfo._dealer.getCode() + " " + rankingInfo._dealer.getName());
            htmlBuilder.AppendFormat(REPORT_CELL_TEMPLATE, (rankingInfo._value * 100).ToString("0.0"));
            htmlBuilder.Append("</tr>");
        }

        reportTableHtml.Text = htmlBuilder.ToString();


        base.RenderComplete();
        renderTime.Text = base.getElapsedRenderTime().ToString();

    }

    public class RankingInfo : IComparable<RankingInfo>
    {
        public dealerDefinition _dealer;
        public double _value;

        public RankingInfo(dealerDefinition dealer, double value)
        {
            this._dealer = dealer;
            this._value = value;
        }

        public int CompareTo(RankingInfo other)
        {
            return other._value.CompareTo(this._value);
        }
    }
}
